<?php

class MerchantController extends ApiController
{
	/**
	 * Get merchant info.
	 * @param type $hid
	 * @param type $key 
	 */
	public function actionIndex() {
		$hid = Yii::app()->request->getParam('hid', null);
		$key = Yii::app()->request->getParam('key', null);
		$id = $this->_auth($hid, $key);
		
		//1. fetch merchants + tags
		$sql_merchant = 'SELECT m.id, m.name, m.address, m.postcode, m.phone, m.city, m.country_code, m.currency_code,
			m.url_logo, m.url_site, m.latitude, m.longitude, m.opening, m.brief
			FROM tbl_merchant_account m
			WHERE password is not null AND id=:id ';
		$connection = Yii::app()->db;
		$command = $connection->createCommand($sql_merchant);
		$row = $command->queryRow(true, array('id'=>$id));
		
		//2. fetch merchant tags
		$sql_tags = 'SELECT cuisine_style, cuisine_type, meal_served '
			//. ', payment_options, service_languages '
			//. ', alcohol_license, dining_ambience, car_parking, additional_details '
			. 'FROM tbl_merchant_tags WHERE id_merchant=:id_merchant';
		$command = $connection->createCommand($sql_tags);
		$tags = $command->queryRow(true, array('id_merchant'=>$id));
		
		//3. get merchant's open hours
		$sql_hours = 'SELECT week_no, open_hour, close_hour FROM tbl_merchant_open_hours
			WHERE id_merchant=:id_merchant ORDER BY week_no ASC';
		$command = $connection->createCommand($sql_hours);
		$aHours = $command->queryAll(true, array('id_merchant'=>$id));
		$connection->active = false;
		
		//handle info
		$response = array(
			'name' => (string)$row['name'],
			'address' => (string)$row['address'],
			'postal_code' => (string)$row['postcode'],
			'city' => (string)$row['city'],
			'phone' => (string)$row['phone'],
			'currency_code' => (string)$row['currency_code'],
			'url_logo' => (string)$url_logo,
			'url_site' => (string)$row['url_site'],
			'brief' => (string)$row['brief'],
		);
		$response['url_logo'] = empty($row['url_logo']) ? '' : 'http://business.yamii.fi' . $row['url_logo'];
		//set tags text
		$response['tags'] = array();
		if (!empty($tags)) {
			foreach ($tags as $key => $value) {
				if (!empty($value)) {
					$array = explode(',', $value);
					foreach ($array as $item) {
						$response['tags'][] = array(
							$item,
							BUtils::T($item),
						);
					}
				}
			}
		}
		
		$this->_sendJSON(200, $response);
	}
}